package com.neusoft.Interceptor;

import com.neusoft.exception.TokenException;
import com.neusoft.util.TokenUtil;
import com.neusoft.util.UserThreadUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class TokenVerifyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //axios方式请求数据时需要先进行一次options方式的预检，预检无法携带token，直接放行
        //如果请求方式是options，直接放行
        if(request.getMethod().equalsIgnoreCase("options")) {
            return true;
        }
        //前置：进入Controller方法之前
        String token = request.getHeader("token");
        if(token == null || token.isEmpty()) {
            //前端没有提供token令牌
            throw new TokenException();
        }
        //利用token解析出empid
        String id = TokenUtil.verifyToken(token);
        if(id == null || id.isEmpty()) {
            //前端提供的是错误的token令牌或token令牌过期了
            throw new TokenException();
        }
        Long empid = Long.parseLong(id);
        //将Token解析出的empid绑定到当前线程上
        //后续通过UserThreadUtil.getEmpId可以直接利用当前线程获得用户ID
        UserThreadUtil.setEmpId(empid);

        //返回值：true放行   false拦截
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
